package com.yikes.srb.web.utils;

import com.yikes.srb.common.enums.ResultCodeEnum;
import com.yikes.srb.common.utils.object.BeanUtils;
import com.yikes.srb.web.exception.BizException;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  实体属性复制
 * </p>
 *
 * @Author: guanrong.yin
 * @Date: 2024/12/1 22:14
 */
@Slf4j
public class BeanConvert {


    /**
     * bean转换
     *
     * @param obj   源bean对象
     * @param clazz 目标 bean 的类型
     * @param <T>   泛型
     * @return 目标bean对象
     */
    public static <T> T toBean(@NotNull Object obj, @NotNull Class<T> clazz) {

        try {
            Constructor<T> constructor = clazz.getDeclaredConstructor();
            T bean = constructor.newInstance();
            // copyProperties 方法里的参数不能为null
            BeanUtils.copyProperties(obj, bean);
            return bean;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            log.warn("bean转换异常:{}", e);
            throw BizException.build(ResultCodeEnum.SYSTEM_EXECUTION_ERROR);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * beanList转换
     *
     * @param list  源bean对象集
     * @param clazz 目标 bean的类型
     * @param <T>   泛型
     * @return 目标bean对象集
     */
    public static <T> List<T> toBeanList(@NotNull List<?> list, @NotNull Class<T> clazz) {

        return list.stream().map(it -> toBean(it, clazz)).collect(Collectors.toList());
    }


}
